#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:imgUtils.py
# author: 马国鑫
# datetime:2022/6/6 17:37
# software: PyCharm

"""
    图片的工具类
"""
import os
from uuid import uuid4
from utils.response_code import RET, error_map_EN

base_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

upload_dir = os.path.join(base_dir, 'app\images')


def generate_path(img):
    """保存图片到本地 + 生成图片路径"""
    if not img:
        return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'data': {'error': '传回的是一个空数据'}}

    # 判断是不是传回正确的图片格式
    end_name = img.filename.rsplit('.')[-1]
    true_format_pic = ['jpg', 'png', 'gif', 'jpeg']

    if end_name not in true_format_pic:
        return {'code': RET.DATAERR, 'message': error_map_EN[RET.DATAERR], 'data': {'error': '传回的是一个错误格式的图片'}}

    # 拼接图片保存路径
    file_name = str(uuid4()) + '.' + end_name

    img_path = os.path.join(upload_dir, file_name)

    img.save(img_path)

    # 返回的是相对路径
    relative_path = '/app/images/' + file_name

    return relative_path


def generate_img_stream(img_path):
    """通过图片路径，读取图片，返回图片base64流"""
    import base64
    img_stream = ''
    img_local_path = base_dir + img_path
    with open(img_local_path, 'rb') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream).decode()
    return img_stream

    # return base_dir + img_path

